package com.ym521.facecheck.utils

import android.graphics.Bitmap
import androidx.core.util.Pools
import com.ym521.facecheck.bean.ImageBitmap

/**
 *@author Ym
 *E-mail: 2435970206@qq.com
 *createTime:2024/6/22
 *explain:
 * 图像帧集的池
 */
internal object ImagePool {
    private val bitmapPool = Pools.SimplePool<ImageBitmap>(10)

    /**
     * 获取
     */
    fun applyImage(width: Int, height: Int, config: Bitmap.Config): ImageBitmap {
        var imageBitmap = bitmapPool.acquire()
        if ((imageBitmap == null) || imageBitmap.bitmap.isRecycled || (imageBitmap.bitmap.width != width) ||
            (imageBitmap.bitmap.height != height) || (imageBitmap.bitmap.config != config)) {
            val bitmap = Bitmap.createBitmap(width, height, config)
            imageBitmap = ImageBitmap(bitmap)
        }
        imageBitmap.time = System.currentTimeMillis()
        return imageBitmap
    }

    fun applyImage(bitmap: Bitmap): ImageBitmap {
        var imageBitmap = bitmapPool.acquire()
        if ((imageBitmap == null) || imageBitmap.bitmap.isRecycled || (imageBitmap.bitmap.width != bitmap.width) ||
            (imageBitmap.bitmap.height != bitmap.height) || (imageBitmap.bitmap.config != bitmap.config)) {
            imageBitmap = ImageBitmap(bitmap)
        }
        imageBitmap.time = System.currentTimeMillis()
        return imageBitmap
    }

    fun releaseImage(imageBitmap: ImageBitmap) {
        if (!imageBitmap.bitmap.isRecycled) {
            bitmapPool.release(imageBitmap)
        }
    }
}